package com.project.module.utill;



import io.jsonwebtoken.*;

import java.util.Date;

/**
 * JWT 工具包
 */
public class JwtUtils {

    /**
     * 密钥
     */
    public static final String SECRET_KEY = "secretKey";
    /**
     * 创建token
     * 将携带的信息放入到token中，并创建token,可重写
     *
     * @param subject
     * @return
     */
    public static String createJWT(String subject, long ttlMillis) {
        //加密方式
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        JwtBuilder builder = Jwts.builder()
                .setSubject(subject)
                .signWith(signatureAlgorithm, SECRET_KEY);
        if (ttlMillis >= 0) {
            //设置过期时间
            long expMillis = System.currentTimeMillis() + ttlMillis;
            builder.setExpiration(new Date(expMillis));
        }
        return builder.compact();
    }


   /* public static String createJWT(String subject, CSCECUser user, long ttlMillis) {
        //加密方式
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        JwtBuilder builder = Jwts.builder()
                .setSubject(subject)
                .claim("USER",user)
                .signWith(signatureAlgorithm, SECRET_KEY);
        if (ttlMillis >= 0) {
            long expMillis = System.currentTimeMillis() + ttlMillis;
            builder.setExpiration(new Date(expMillis));
        }
        return builder.compact();
    }*/

    /**
     * 验证JWT
     *
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJWT(String jwtStr) {
        CheckResult checkResult = new CheckResult();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            checkResult.setSuccess(true);
            checkResult.setMsg("验证成功");
            checkResult.setClaims(claims);
        } catch (ExpiredJwtException e) {
            checkResult.setSuccess(false);
            checkResult.setMsg("token已经过期");
        } catch (SignatureException e) {
            checkResult.setSuccess(false);
            checkResult.setMsg("token验证失败");
        } catch (Exception e) {
            checkResult.setSuccess(false);
            checkResult.setMsg("token验证失败");
        }
        return checkResult;
    }

    /**
     * 解析jwt
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt){
        return Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(jwt).getBody();

    }


    /**64位编码生成key
     * @return
     */
  /* public static SecretKey generalKey() {
        byte[] encodeKey = Base64.decode("7786df7fc3a34e26a61c034d5ec8245d");
        SecretKey secretKey = new SecretKeySpec(encodeKey, 0, encodeKey.length, "AES");
        return secretKey;

    }
*/

}
